/**
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

package buses;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 * A class responsible for the caching of Lines using RecordStores
 * 
 * @author Dor Shemer
 */
public class Cache {

	// the RecordStore name
	private static final String RS_NAME = "busses";

	/**
	 * Initializes the Caching machanism.
	 * Checks whether the machanism was initialized sometime earlier this day, and if not (e.g initialized in a previous
	 * day or never initialized) creates a new RecordStore for caching.
	 * 
	 * This should normally be called only when the application is starting.
	 * 
	 * @throws RecordStoreException
	 */
	public static void init() throws RecordStoreException {
		RecordStore rs = null;
		try {
			// gets the caching RecordStore
			 rs = getRecordStore();
			
			// checking for the last cache init date
			Date lastInit = null;
			if (rs.getNumRecords()>0) {			
				byte[] b = rs.getRecord(1);
				if (b!=null) {
					lastInit = new Date(bytesToLong(b));
				}
			}
	
			Date now = new Date();
			if (lastInit!=null) {
				if (areTheSameDay(lastInit, now)) {
					// the cache data is valid for the current day. nothing else to do
					return;
				}
				
				// the cache data is invalid for the current day. flushing cache
				rs.closeRecordStore();
				RecordStore.deleteRecordStore(RS_NAME);
				rs = getRecordStore();
			}
			
			// writing the current time to the cache header
			byte[] b = longToBytes(now.getTime());
			rs.addRecord(b, 0, b.length);
		} finally {
			if (rs!=null) rs.closeRecordStore();
		}
	}
	
	/**
	 * Checks whether two Date objects represent the same day
	 */
	private static boolean areTheSameDay(Date d1, Date d2) {
		// converting the Date objects to Calendars
		Calendar c1 = Calendar.getInstance();
		c1.setTime(d1);
		Calendar c2 = Calendar.getInstance();
		c2.setTime(d2);
		
		return 	c1.get(Calendar.DATE)==c2.get(Calendar.DATE) && 
				c1.get(Calendar.MONTH)==c2.get(Calendar.MONTH) &&
				c1.get(Calendar.YEAR)==c2.get(Calendar.YEAR);
	}
	
	
	/**
	 * Retrieves the cached Line for the given line number, if exists
	 * @param lineNumber
	 * @return the cached Line object, or null if this line number isn't cached
	 * 
	 * @throws RecordStoreException
	 * @throws IOException
	 */
	public static Line retrieve(int lineNumber) throws RecordStoreException, IOException {
		RecordStore rs = getRecordStore();
		try {
			// searching for the line number in the RecordStore
			RecordEnumeration re = findData(rs, lineNumber);
			if (!re.hasNextElement()) {
				// no elements returned, thus the line is not cached
				return null;
			}
			
			// creating a Line object using the cached line data block, and returning it
			return new Line(re.nextRecord());
		} finally {
			if (rs!=null) rs.closeRecordStore();
		}
	}
	
	/**
	 * Stores a Line object to the cache
	 * 
	 * @param line
	 * @return the cached record's ID in the cache RecordStore
	 * @throws RecordStoreException
	 * @throws IOException
	 */
	public static int store(Line line) throws RecordStoreException, IOException {
		RecordStore rs = getRecordStore();		
		try {
			int id = -1;
			
			// checking if the line is already cached 
			RecordEnumeration re = findData(rs, line.lineNumber);
			if (re.hasNextElement()) {
				// the line is cached, replacing the cached object with the given one
				id = re.nextRecordId();
				rs.setRecord(id, line.data, 0, line.data.length);
			} else {
				// the line is not cached, adding it to the cache
				id = rs.addRecord(line.data, 0, line.data.length);
			}
			
			// returning the record's ID in the cache RecordStore
			return id;
			
		} finally {
			if (rs!=null) rs.closeRecordStore();
		}
	}
	
	
	/**
	 * Returns a RecordEnumeartion object enumerating over all the records in a RecordStore that have the
	 * given line number.
	 * The returned RecordEnumeration should will have no records to enumerate over if the line is not cached, or one
	 * if it is. It should never have more than one record to enumerate over
	 * 
	 * @param rs
	 * @param lineNumber
	 * @return
	 * @throws RecordStoreException
	 * @throws IOException
	 */
	private static RecordEnumeration findData(RecordStore rs, int lineNumber) throws RecordStoreException, IOException  {
		return rs.enumerateRecords(filter(lineNumber), null, false);		
	}
	
	/***
	 * Gets the caching RecordStore, creating it if doesn't exist
	 * 
	 * @return
	 * @throws RecordStoreException
	 */
	private static RecordStore getRecordStore() throws RecordStoreException {
		return RecordStore.openRecordStore(RS_NAME, true);
	}
	
	/**
	 * Creates and returns a RecordFilter to use when searching for a line in a RecordStore by its number
	 * 
	 * @param lineNumber
	 * @return
	 */
	private static RecordFilter filter(final int lineNumber) {
		return new RecordFilter(){
			public boolean matches(byte[] b) {
				// checks whether the line numbers are equal
				return b.length>2 && Line.parseLineNumber(b)==lineNumber;
			}
		};
	}
	
	/**
	 * Converts a long to a new big-endian byte array
	 * @param l
	 * @return
	 */
	private static byte[] longToBytes(long l) {
		byte[] b = new byte[8];
		for (int i=0; i<8; i++) {
			b[i] = (byte)((l>>8*i)&0xff);
		}
		return b;
	}
	
	/**
	 * Converts a big-endian byte array to a long
	 * @param l
	 * @return
	 */
	private static long bytesToLong(byte[] b) {
		long l=0;
		for (int i=7; i>=0; i--) {
			l<<=8;
			l+=(b[i]&0x00ff);
		}
		return l;
	}
	

	/**
	 * A non-persistant cache, used for storing objects in the application memory for later usage 
	 * @author Dor Shemer
	 */
	public static class ShortCache {
		private Object cachingObject;
		private Object cache[];
		private boolean dirty = false;
		
		/**
		 * Creates a new ShortCache object if a given length
		 * @param length
		 */
		public ShortCache(int length) {
			cache = new Object[length];
		}
		
		/**
		 * Sets the caching object, which is used to determin whether the cached data is valid upon retrival
		 * @param cachingObject
		 */
		public void setCachingObject(Object cachingObject) {
			this.cachingObject = cachingObject;
			if (dirty) {
				// clearing the cache array
				for (int i=0; i<cache.length; i++) {
					cache[i] = null;
				}
				dirty = false;
			}			
		}
		
		/**
		 * Determines wheter the given object is the current caching object
		 * @param obj
		 * @return
		 */
		public boolean isCachingObject(Object obj) {
			return obj.equals(this.cachingObject);
		}
		
		/**
		 * Retreieves the cached object at a given index, if exists
		 * @param index
		 * @return the cached object, or null if it doesn't exist
		 */
		public Object retrieve(int index) {
			return dirty && cache.length>index ? cache[index] : null;
		}
		
		/**
		 * Stores an object in a given index
		 * @param obj
		 * @param index
		 */
		public void store(Object obj, int index) {
			cache[index] = obj;
			dirty = true;
		}
	}
}
